package com.jone.bang;



import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.jone.bang.db.ConfigCenter;
import com.jone.bang.model.BChannel;
import com.jone.bang.model.GalleryAdapter;
import com.jone.bang.model.WordItem;
import com.jone.bang.service.DownloadService;
import com.jone.bang.service.FileManager;
import com.jone.bang.util.Constant;
import com.jone.bang.util.MyHtmlReader;
import com.wooboo.adlib_android.WoobooAdView;

public class HomeActivity extends Activity implements WoobooAdView.ER{
	
	private static final int RSS_LOAD_FINISH = 1;
	
	private static final int CONTENT_LOAD_FINISH = 10;
	
	private static final int GALLERY_REFRESH = 20;
	
	private static final int HIDE_MYSELEF_AD = 30;
	
	private static final int SHOW_MYSELEF_AD = 40;
	
	public static final int DIALOG_LIST = 1;
	
	private static final int LOAD_DIALOG = 2;
	
	private static final int DIALOG_HELP = 3;
	
	private static final int DIALOG_CONFIG = 4;
	
	final String mimeType = "text/html";
    final String encoding = "utf-8";
	
	private DownloadService downloadService;
	
	private String[] keywords;
		
	private Gallery tabs;
	
	private TextView mainTest;
	
	private LinearLayout mainLayout;
	
	private LayoutInflater factory;
	
	private WebView webView;
	
	private View listView;
	
	private WoobooAdView ad;
	
	private ImageView adImg;
	
	private String content;
	
	private String curId = "1";
	
	private String curSearchWord;
	
	private String curName;
	
	private boolean mainHasLoaded = false;
	
	private int galleryPosition = 0;
	
	private Handler handler = new Handler(){
		  public void handleMessage(Message message){
		   switch(message.what){
		   case CONTENT_LOAD_FINISH:		    	
		    	mainLayout.setVisibility(View.GONE);
		    	webView.setVisibility(View.VISIBLE);	
		    	dismissDialog(LOAD_DIALOG);	
		    	break;
		   case GALLERY_REFRESH:
			   galleryPosition++;
			   if(galleryPosition >= tabs.getCount()){
				   galleryPosition = 0;
			   }
			   tabs.setSelection(galleryPosition, true);
			   break;
		   case HIDE_MYSELEF_AD:
			   if(adImg.getVisibility() != View.GONE){
				   adImg.setVisibility(View.GONE);
			   }
			   break;
		   case SHOW_MYSELEF_AD:
			   if(adImg.getVisibility() != View.VISIBLE){
				   adImg.setVisibility(View.VISIBLE);
			   }
			   break;			   
		   case RSS_LOAD_FINISH:
//		    	mainTest.setText(content);
		    	mainLayout.setVisibility(View.VISIBLE);
		    	//为了下次Visble的时候不显示上次的内容，将webView置空
//		    	webView.loadData("", mimeType, encoding);
		    	webView.setVisibility(View.GONE);
		    	
		    	TextView title = (TextView)listView.findViewById(R.id.tab_title);
		    	title.setText(curName+"排行榜");
		    	ListView dataList = (ListView)listView.findViewById(R.id.contentList);
		    	
		    	dismissDialog(LOAD_DIALOG);	
		    	if(keywords!= null){
		    		dataList.setAdapter(new ArrayAdapter<String>(HomeActivity.this,
			                R.layout.list_item, keywords));
		    		dataList.setOnItemClickListener(new OnItemClickListener(){

						@Override
						public void onItemClick(AdapterView<?> adapterView, View v,
								int position, long id) {						
							showDialog(LOAD_DIALOG);				    	
							try {
								curSearchWord = URLEncoder.encode(keywords[position], "GBK");
							} catch (UnsupportedEncodingException e) {
								Log.e("HomeActivity", "URLEncoder encode error:["+keywords[position]);
							}
							new Thread(){
			            		   public void run(){			            			   
			            			   webView.loadUrl("http://m.baidu.com/s?word="+curSearchWord);			            			   
			            			   try {
										Thread.sleep(1500);
									} catch (InterruptedException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
			            			   Message loadFinish = new Message();
			            			   loadFinish.what = CONTENT_LOAD_FINISH;
			               		    	handler.sendMessage(loadFinish);
			            		   }
			            	}.start();
					    	
						}
		    			
		    		});
		    		if(!mainHasLoaded){
			    		mainLayout.addView(listView);
			    		mainHasLoaded = true;
			    	}
		    	}
		    break;		   
		   }
		   super.handleMessage(message);
		  }
	};


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);  
        
        NotificationManager nfManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    	nfManager.cancel(118);
    	
        mainLayout = (LinearLayout)this.findViewById(R.id.mainFrame);    
        factory = LayoutInflater.from(this);         
        listView = factory.inflate(R.layout.list, null);  
//        ad = (AdView)this.findViewById(R.id.ad);
//        //设置广告获取监听器
//        ad.setListener(this);
  
//        adImg = (ImageView)this.findViewById(R.id.ad_myselef);
//        
//      
//        adImg.setOnClickListener(new OnClickListener(){
//			@Override
//			public void onClick(View v) {
//				showDialog(DIALOG_HELP);				
//			}        	
//        });
        
        webView = (WebView)this.findViewById(R.id.wv1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setDefaultFontSize(18);
        webView.setWebViewClient(new WebViewClient(){  
            public boolean shouldOverrideUrlLoading(WebView view, String url) {  
            	try{
                	String data = MyHtmlReader.load(url);
                    FileManager.saveHtml(data);
                	webView.loadUrl("content://com.android.htmlfileprovider/sdcard/temp_html.html");            
                }catch(Exception e){
                	Toast.makeText(HomeActivity.this, "需要缓存，请插入SD卡", Toast.LENGTH_LONG).show();
                	return true; 
                }                      
                return true;  
            }  
            
            @Override
			public void onPageFinished(WebView view, String url) {
            	Log.d("WebView","onPageFinished");
            	dismissDialog(LOAD_DIALOG);	    
            	webView.requestFocus();
				super.onPageFinished(view, url);
			}
            
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				Log.d("WebView","onPageStarted,url="+url);
				showDialog(LOAD_DIALOG);    
				super.onPageStarted(view, url, favicon);
			}
        });  
//        webView.loadData("", mimeType, encoding);
        
        downloadService = new DownloadService(getApplicationContext());    
        tabs = (Gallery)this.findViewById(R.id.channel_gallery);
//        Cursor c = getContentResolver().query(BChannel.CHANNEL, null, null, null, BChannel._ID+" asc");
//        startManagingCursor(c);        
//        SpinnerAdapter adapter = new SimpleCursorAdapter(this,   
//                R.layout.gallery_item,
//                c,
//                new String[] {BChannel.NAME},
//                new int[] { R.id.item_name});
//        tabs.setAdapter(adapter);
        //需要与数据库中的项目保持一致
        String[] channels = {"今日飙升","一周热点","焦点人物","热门电影","热播电视","畅销书"};
        tabs.setAdapter(new GalleryAdapter(this,channels));
        
        tabs.setSelection(1);
        tabs.setOnItemClickListener(new OnItemClickListener() {
            @SuppressWarnings("unchecked")
			public void onItemClick(AdapterView parent, View v, int position, long id) {
            	showDialog(LOAD_DIALOG);
            	curId = String.valueOf(id);
            	new Thread(){
            		   public void run(){
            			content = getItems(curId);
            		    Message loadFinish = new Message();
            		    loadFinish.what = RSS_LOAD_FINISH;
            		    handler.sendMessage(loadFinish);
            		   }
            	}.start();
            }
        });
        
        
        
        //打开mainLayout
        showDialog(LOAD_DIALOG);    	
    	new Thread(){
    		   public void run(){
    			content = getItems(curId);
    		    Message loadFinish = new Message();
    		    loadFinish.what = RSS_LOAD_FINISH;
    		    handler.sendMessage(loadFinish);
    		   }
    	}.start();
    	
    	//控制gallery横条移动
    	Timer mTimer = new Timer();
		mTimer.schedule(new TimerTask() {
			public void run() {
				// do..
				Message refresh = new Message();
				refresh.what = GALLERY_REFRESH;
    		    handler.sendMessage(refresh);
			}
		}, 5000,5000);
    	
    	if(!ConfigCenter.getValue(getApplicationContext(), Constant.KEY_WIDGET_ADDED, false)){
    		Toast.makeText(getApplicationContext(), "温馨提示：\n在桌面上添加该软件的小部件可以更方便的获取资讯！", Toast.LENGTH_LONG).show();
    	}
    	
    } 
    
    private String getItems(String id){
    	String key = null;
    	String name = null;
    	StringBuffer sb = new StringBuffer();
    	Cursor c = getContentResolver().query(BChannel.CHANNEL, null, BChannel._ID+"="+id, null, null);
    	startManagingCursor(c);
    	if(c!= null && c.moveToFirst()){
    		key = c.getString(c.getColumnIndex(BChannel.KEY));
    		name = c.getString(c.getColumnIndex(BChannel.NAME));
    		
        	List<WordItem> list = downloadService.getList(key);
        	if(list != null && !list.isEmpty()){
        		keywords = new String[list.size()];
        		for(int i =0;i<list.size();i++){
        			keywords[i] = list.get(i).getName();
        			sb.append(list.get(i).getName()).append("\n");
        		}
        	}
    	}
    	curName = name;
    	return sb.toString();
    }
    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {           
            case LOAD_DIALOG: {
                ProgressDialog dialog = new ProgressDialog(this);
                dialog.setMessage("Loading...");
                dialog.setIndeterminate(true);
                dialog.setCancelable(true);
                return dialog;
            }
            case DIALOG_HELP:
	            return new AlertDialog.Builder(HomeActivity.this)
	                .setIcon(R.drawable.alert_dialog_icon)
	                .setTitle("帮助")
	                .setMessage(R.string.help)
	                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	                    public void onClick(DialogInterface dialog, int whichButton) {

	                        /* User clicked OK so do some stuff */
	                    }
	                })	                
	                .create();
            case DIALOG_CONFIG:
            	LayoutInflater factory = LayoutInflater.from(this);
                final View textEntryView = factory.inflate(R.layout.config, null);
                CheckBox chk = (CheckBox)textEntryView.findViewById(R.id.chk_enable_notify);
                chk.setChecked(ConfigCenter.getValue(this, Constant.KEY_ENABLE_NOTIFICATION, true));
                return new AlertDialog.Builder(HomeActivity.this)
                    .setIcon(R.drawable.alert_dialog_icon)
                    .setTitle("设置")
                    .setView(textEntryView)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                        	CheckBox chkbox = (CheckBox)textEntryView.findViewById(R.id.chk_enable_notify);
                        	ConfigCenter.setValue(getApplicationContext(), Constant.KEY_ENABLE_NOTIFICATION, chkbox.isChecked());
                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {

                            /* User clicked cancel so do some stuff */
                        }
                    })
                    .create();
        }
        return null;
    }
    
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {  
        	if(webView.canGoBack()){
        		webView.goBack();  
        		//因为曾经置空，最后一个回退的是空界面，所以就返回主界面
//        		if(webView.getUrl().equals("data:text/html;utf-8,")){
//        			content = getItems(curId);
//        		    Message loadFinish = new Message();
//        		    loadFinish.what = RSS_LOAD_FINISH;
//        		    handler.sendMessage(loadFinish);
//        		    return true;
//        		}
                return true; 
        	}else if(mainLayout.getVisibility()!= View.VISIBLE){
        		
        		content = getItems(curId);
    		    Message loadFinish = new Message();
    		    loadFinish.what = RSS_LOAD_FINISH;
    		    handler.sendMessage(loadFinish);
    		    return true;
        	}
             
        }  
        return super.onKeyDown(keyCode, event);  
    }  
    
//    public void onResume(){
//    	dismissDialog(LOAD_DIALOG);	
//    	content = getItems(curId);
//	    Message loadFinish = new Message();
//	    loadFinish.what = RSS_LOAD_FINISH;
//	    handler.sendMessage(loadFinish);
//	    super.onResume();
//    }
    
    public void onDestroy () {
    	
    	Log.d("HomeActivity", "onDestroy");
    	webView.clearCache(true);
    	super.onDestroy();
    }



	@Override
	public void onFailedToReceiveAd(WoobooAdView arg0) {
		Log.d("AdListener", "onFailedToReceiveAd");
		
		Message loadFinish = new Message();
		loadFinish.what = SHOW_MYSELEF_AD;
	    handler.sendMessage(loadFinish);
	}



	@Override
	public void onNewAd() {
		Log.d("AdListener", "onNewAd");
	}



	@Override
	public void onReceiveAd(WoobooAdView arg0) {
		Log.d("AdListener", "onReceiveAd");		
		Message loadFinish = new Message();
		loadFinish.what = HIDE_MYSELEF_AD;
	    handler.sendMessage(loadFinish);
	}
	
	 @Override
		public boolean onCreateOptionsMenu(Menu menu) {
	    	MenuInflater inflater = getMenuInflater();
	    	inflater.inflate(R.menu.menu_main, menu);
	    	return true;
		}
	    
	    @Override
		public boolean onOptionsItemSelected(MenuItem item) {
	    	switch (item.getItemId()) {
			case R.id.menu_help:
				showDialog(DIALOG_HELP);   
				break;	
			case R.id.menu_config:
				showDialog(DIALOG_CONFIG);   
				break;	
			default:
				throw new IllegalArgumentException("Unknown Operator");
			}
	    	return true;
	    }
	
}